package com.yaodian100.ec.cobranding.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.digester.BeanPropertySetterRule;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.ObjectCreateRule;
import org.apache.commons.digester.Rules;
import org.apache.commons.digester.SetNextRule;
import org.apache.commons.digester.SetPropertiesRule;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.cobranding.entity.Hao123;
import com.yaodian100.ec.cobranding.entity.Hao123Coordinates;
import com.yaodian100.ec.cobranding.entity.Marketingxml;
import com.yaodian100.ec.cobranding.service.Hao123Service;
import com.yaodian100.ec.cobranding.service.MarketingXMLService;

public class Hao123ServiceImpl implements Hao123Service {
	@Resource
	MarketingXMLService mktXMLService;
	private static String HAO123_XML_FILEPATH = ServerValue.getMidApachePath() + "3party_ex" + File.separator;
	private static String HAO123_XML_FILENAME = "hao123.xml";

	@Override
	public String makeCompleteXML(String loc, String website) {
		long timeStamp = new Date().getTime();
		try {

			Document doc = DocumentHelper.createDocument();
			// 主檔
			Element rootElement = doc.addElement("urlset").addElement("url");
			rootElement.addElement("loc").addText(loc);
			rootElement.addElement("website").addText(website);
			// 明細檔
			List<Marketingxml> mktXMLs = mktXMLService.getHao123XML();
			for (Marketingxml mktXML : mktXMLs) {

				Document data = DocumentHelper.parseText(mktXML.getXmlContent());

				rootElement.add(data.getRootElement());
			}
			File f = new File(HAO123_XML_FILEPATH);
			if (!f.exists()) {
				f.mkdirs();
			} else {
				timeStamp = f.lastModified();
			}
			FileUtils.writeStringToFile(new File(HAO123_XML_FILEPATH + HAO123_XML_FILENAME), doc.asXML(), "UTF-8");

			// FileOutputStream fos = new FileOutputStream(HAO123_XML_FILEPATH + HAO123_XML_FILENAME);
			// OutputFormat format = OutputFormat.createPrettyPrint();
			// XMLWriter writer = new XMLWriter(fos, format);
			// writer.write(doc);
			// writer.flush();
		} catch (Exception e) {

			e.printStackTrace();
		}
		File xmlFile = new File(HAO123_XML_FILEPATH + HAO123_XML_FILENAME);
		String xmlWebPath = "";
		if (xmlFile.exists()) {
			if (xmlFile.lastModified() >= timeStamp) {
				xmlWebPath = ServerValue.getMidHostname() + "/3party_ex/hao123.xml";
			}
		}

		return xmlWebPath;
	}

	@Override
	public Marketingxml saveHao123XML(String mrkXMLId, Hao123 hao123) {
		String xmlContent = makeHao123XML(hao123);

		Marketingxml mktXML = new Marketingxml();

		if (StringUtils.isNotBlank(mrkXMLId)) {
			mktXML = mktXMLService.get(mrkXMLId);
		}

		mktXML.setXmlType("hao123");
		mktXML.setXmlContent(xmlContent);

		if (StringUtils.isNotBlank(mktXML.getId())) {
			mktXML = mktXMLService.update(mktXML);
		} else {
			mktXML = mktXMLService.save(mktXML);
		}

		return mktXML;
	}

	@Override
	public HashMap<String, String> getHao123Main() {
		HashMap<String, String> mainMap = new HashMap<String, String>();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {

			File xml = new File(HAO123_XML_FILEPATH + HAO123_XML_FILENAME);
			if (xml.exists()) {
				Date fileLatModify = new Date();
				fileLatModify.setTime(xml.lastModified());
				mainMap.put("lastModify", df.format(fileLatModify));
				SAXReader saxReader = new SAXReader();
				Document document = saxReader.read(xml);
				Element urlset = document.getRootElement();

				for (Iterator<Element> i = urlset.elementIterator("url"); i.hasNext();) {
					Element url = i.next();
					for (Iterator<Element> it = url.elementIterator(); it.hasNext();) {
						Element thisElement = it.next();
						if ("loc".equals(thisElement.getName())) {
							mainMap.put("loc", thisElement.getText());
						}
						if ("website".equals(thisElement.getName())) {

							mainMap.put("website", thisElement.getText());
						}
					}

				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return mainMap;
	}

	@Override
	public List<Hao123> getHao123() {
		List<Hao123> hao123s = new ArrayList<Hao123>();
		try {
			List<Marketingxml> mktXMLs = mktXMLService.getHao123XML();
			for (Marketingxml mktXML : mktXMLs) {
				InputStream is = new ByteArrayInputStream(mktXML.getXmlContent().getBytes("UTF-8"));
				List<Hao123> temp = new ArrayList<Hao123>();
				Digester digester = getParseDigesterDetail();
				digester.push(temp);
				Object root = digester.parse(is);
				if (temp.size() > 0) {
					Hao123 hao123 = temp.get(0);

					Date startDate = new Date();
					startDate.setTime(Long.parseLong(hao123.getStrStartTime()) * 1000);
					hao123.setStartTime(startDate);
					Date endDate = new Date();
					endDate.setTime(Long.parseLong(hao123.getStrEndTime()) * 1000);
					hao123.setEndTime(endDate);

					hao123.setMktXMLId(mktXML.getId());

					hao123s.add(hao123);
				}
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
		return hao123s;
	}

	@Override
	public Hao123 getHao123Deatil(String id) {
		Hao123 hao123 = null;

		try {
			Marketingxml mktXML = mktXMLService.get(id);
			if (null != mktXML) {
				String xmlContent = mktXML.getXmlContent();
				InputStream is = new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));

				List<Hao123> temp = new ArrayList<Hao123>();
				Digester digester = getParseDigesterDetail();
				digester.push(temp);
				Object root = digester.parse(is);
				if (temp.size() > 0) {
					hao123 = temp.get(0);
					Date startDate = new Date();
					startDate.setTime(Long.parseLong(hao123.getStrStartTime()) * 1000);
					hao123.setStartTime(startDate);
					Date endDate = new Date();
					endDate.setTime(Long.parseLong(hao123.getStrEndTime()) * 1000);
					hao123.setEndTime(endDate);

					hao123.setMktXMLId(mktXML.getId());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hao123;
	}

	private Digester getParseDigesterDetail() {
		Digester digester = new Digester();
		Rules rules = digester.getRules();
		rules.add("data", new ObjectCreateRule("com.yaodian100.ec.cobranding.entity.Hao123"));
		rules.add("data", new SetNextRule("add", "com.yaodian100.ec.cobranding.entity.Hao123"));
		rules.add("data", new SetPropertiesRule());
		rules.add("data/display/website", new BeanPropertySetterRule("website"));
		rules.add("data/display/activityurl", new BeanPropertySetterRule("activityurl"));
		rules.add("data/display/category", new BeanPropertySetterRule("category"));
		rules.add("data/display/keyword1", new BeanPropertySetterRule("keyword1"));
		rules.add("data/display/keyword2", new BeanPropertySetterRule("keyword2"));
		rules.add("data/display/keyword3", new BeanPropertySetterRule("keyword3"));
		rules.add("data/display/major", new BeanPropertySetterRule("major"));
		rules.add("data/display/title", new BeanPropertySetterRule("title"));
		rules.add("data/display/sampleimage", new BeanPropertySetterRule("sampleimage"));
		rules.add("data/display/image", new BeanPropertySetterRule("image"));
		rules.add("data/display/startTime", new BeanPropertySetterRule("strStartTime"));
		rules.add("data/display/endTime", new BeanPropertySetterRule("strEndTime"));
		// Add Rules to parse a character element
		rules.add("data/display/set/item", new ObjectCreateRule("com.yaodian100.ec.cobranding.entity.Hao123Coordinates"));
		rules.add("data/display/set/item", new SetNextRule("addSet",
				"com.yaodian100.ec.cobranding.entity.Hao123Coordinates"));
		rules.add("data/display/set/item", new SetPropertiesRule());
		rules.add("data/display/set/item/x1", new BeanPropertySetterRule("x1"));
		rules.add("data/display/set/item/y1", new BeanPropertySetterRule("y1"));
		rules.add("data/display/set/item/x2", new BeanPropertySetterRule("x2"));
		rules.add("data/display/set/item/y2", new BeanPropertySetterRule("y2"));
		rules.add("data/display/set/item/href", new BeanPropertySetterRule("href"));
		rules.add("data/display/set/item/title", new BeanPropertySetterRule("title"));
		return digester;
	}

	private String makeHao123XML(Hao123 hao123) {
		Document returnDocument = DocumentHelper.createDocument();
		Element returnRoot = returnDocument.addElement("data").addElement("display");
		returnRoot.addElement("website").addText(hao123.getWebsite());
		returnRoot.addElement("activityurl").addText(hao123.getActivityurl());
		returnRoot.addElement("category").addText(hao123.getCategory());
		returnRoot.addElement("keyword1").addText(hao123.getKeyword1());
		if (StringUtils.isNotBlank(hao123.getKeyword2())) {
			returnRoot.addElement("keyword2").addText(hao123.getKeyword2());
		}
		if (StringUtils.isNotBlank(hao123.getKeyword3())) {
			returnRoot.addElement("keyword3").addText(hao123.getKeyword3());
		}
		returnRoot.addElement("major").addText(hao123.getMajor());
		returnRoot.addElement("title").addText(hao123.getTitle());
		if (StringUtils.isNotBlank(hao123.getSampleimage())) {
			returnRoot.addElement("sampleimage").addText(hao123.getSampleimage());
		}
		returnRoot.addElement("image").addText(hao123.getImage());
		Element setRoot = returnRoot.addElement("set");
		for (Iterator<Hao123Coordinates> it = hao123.getSet().iterator(); it.hasNext();) {
			Hao123Coordinates hao123Cos = it.next();
			Element items = setRoot.addElement("item");
			items.addElement("x1").addText(hao123Cos.getX1());
			items.addElement("y1").addText(hao123Cos.getY1());
			items.addElement("x2").addText(hao123Cos.getX2());
			items.addElement("y2").addText(hao123Cos.getY2());
			items.addElement("href").addText(hao123Cos.getHref());
			items.addElement("title").addText(hao123Cos.getTitle());
		}
		returnRoot.addElement("startTime").addText(String.valueOf(hao123.getStartTime().getTime() / 1000L));
		returnRoot.addElement("endTime").addText(String.valueOf(hao123.getEndTime().getTime() / 1000L));

		return returnDocument.asXML();
	}

}
